import React, {useState,useEffect} from 'react'
import axios from 'axios'
import './exam.css'
export default function Exam() {
    const [list,setList] = useState([]);
    const [ind, setInd] = useState(0)
    const [answerList, setAnswerList] = useState({})
    useEffect(() => {
        axios.get('http://localhost:7001/list').then(res=>{
            if(res.data.code ===1 ){
                setList(res.data.data)
            }
        })
    }, [])
    const setIndFun = (num) =>{
        setInd(prev=>{
            return prev+=num
        })
    }
    const submit = (prev)=>{
        // {1: 2, 2: 6, 3: "10,11,12", 4: 1, 5: 0}
        // [{id:1,answer:2}, {id:3,asnwer:"10,11,12"}]
        const newList = []
        for(let key in answerList) {
            newList.push({id:key, answer: answerList[key]})
        }
        axios.post('http://localhost:7001/list', {answerList:newList}).then(res=>{
            if(res.data.code===1){
                alert(`您的分数为${res.data.data.allScore}`)
            }
        })
    }
    return (
        <div>
            {list[ind]?<Question item={list[ind]} setAnswerList={setAnswerList} answerList={answerList}></Question>:null}
            {ind!==0?<button onClick={()=>{setIndFun(-1)}}>上一页</button>:null}
            {ind !== list.length-1 ? <button onClick={()=>{setIndFun(1)}}>下一页</button>:null}
            <button onClick={() => {submit()}}>提交</button>
        </div>
    )
}
function Question({item,setAnswerList,answerList}) {
    const QuestionType = {
        radio:"【单选题】",
        multiple:"【多选题】",
        judge:"【判断题】",
    }
    const QuestionLetter = ['A','B',"C","D"]
    const optionsClick = (data)=>{
        if(item.type==='radio') { // 单选
            setAnswerList(prev=>{
                // prev是上一次的值
                prev[item.id] = data.id;
                console.log(prev)
                return JSON.parse(JSON.stringify(prev))
            })
        } else if(item.type === 'multiple') {// 多选
            setAnswerList(prev=>{
                // 判断是不是第一次选中 prev=   1,2,3,4
                let oldList = prev[item.id]?prev[item.id].split(',') :[];
                const ind = oldList.indexOf(String(data.id));
                // 判断是不是已经选中， 如果已经选中则走的是取消选中操作 也就是要剔除掉当前值
                if(oldList.length && ind !== -1) {
                    oldList.splice(ind,1)
                } else {
                    oldList.push(data.id)
                }
                // 由于数据库中打答案是顺序排列的  所以这里要写一个正序排序
                oldList.sort((a,b)=>{
                    return (a*1)-(b*1)
                })
                prev[item.id] = oldList.join(',')
                console.log(prev)
                return JSON.parse(JSON.stringify(prev))
            })
        } else { // 判断
            setAnswerList(prev=>{
                // prev是上一次的值
                prev[item.id] = data === '正确' ? 1 : 0;
                console.log(prev)
                return JSON.parse(JSON.stringify(prev))
            })
        }
    }
    // 判断是否高亮
    const isHave = (id) => {
        if(item.type==='radio'){
            return answerList[item.id] === id;
        } else if (item.type==='multiple') {
            const list = answerList[item.id]?answerList[item.id].split(','):[]
            return list.indexOf(String(id)) !== -1
        } else {
            if(id==='正确') {
                return answerList[item.id] === 1
            } else if(id==='错误') {
                return answerList[item.id] === 0
            } else {
                return false
            }
        }
    }
    return <div>
        {QuestionType[item.type]}{item.title}
        {/* 选项 */}
        {item.checks.length ? item.checks.map((data,ind)=>{
            return <div 
                className={isHave(data.id)?'active':""}
                key={ind} 
                onClick={() => {
                    optionsClick(data)
                }}
            >
                {QuestionLetter[ind]}. {data.content}
            </div>
        }):['正确','错误'].map((data,ind)=>{
            return <div 
                className={isHave(data)?'active':""}
                key={ind}
                onClick={() => {
                    optionsClick(data)
                }}
            >
                {QuestionLetter[ind]}. {data}
            </div>
        })}
    </div>
}